package cn.iocoder.yudao.module.vote.utils;

import cn.hutool.core.util.NumberUtil;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.math.BigDecimal;

/**
 * @description:
 * @author: moving
 * @date: 2023/3/17 16:27
 */
public class CalcEngineUtil {

    private static ScriptEngineManager factory = new ScriptEngineManager();
    private static ScriptEngine engine = factory.getEngineByName("JavaScript");

    /**
     * 默认保留两位
     */
    private static final Integer defaultScale = 2;

    public static BigDecimal calcExpress(String express) {
        return calcExpress(express,defaultScale);
    }

    public static BigDecimal calcExpress(String express,Integer scale) {
        try {
            Object o = engine.eval(express);
            return new BigDecimal(o.toString()).setScale(scale,BigDecimal.ROUND_HALF_UP);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
        return null;
    }


//    public static void main(String[] args){
//        CalcEngineUtil calcEngineUtil = new CalcEngineUtil();
//        BigDecimal result = calcEngineUtil.calcExpress("10*100+8*0.8+9*0.6+7*0.4");
//        System.out.println(result);
//    }


}
